package com.decent.ejfadmin.user.service.impl;

import cn.decent.component.shiro.service.AdminService;
import cn.decent.component.shiro.vo.AdminVO;
import com.decent.ejfadmin.common.bean.*;
import com.decent.ejfadmin.common.enums.SubmitCardApplyEnum;
import com.decent.ejfadmin.common.enums.SupRedisKey;
import com.decent.ejfadmin.common.exception.OperateFailException;
import com.decent.ejfadmin.common.exception.SupException;
import com.decent.ejfadmin.finance.dao.SupplyFinanceDao;
import com.decent.ejfadmin.function.service.PlatConfigService;
import com.decent.ejfadmin.order.dao.OrderDao;
import com.decent.ejfadmin.tools.EmailSend;
import com.decent.ejfadmin.user.dao.SupUserRecordDao;
import com.decent.ejfadmin.user.dao.UserDao;
import com.decent.ejfadmin.user.dao.UserPmDao;
import com.decent.ejfadmin.user.service.UserService;
import com.decent.ejfadmin.utils.Httpclient;
import com.decent.ejfadmin.utils.Md5;
import com.decent.ejfadmin.utils.PlatConfigUtil;
import com.decent.ejfadmin.utils.SimpleCacheUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author weicx
 * @date 2018/07/19
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private SupplyFinanceDao supplyFinanceDao;
    @Autowired
    private UserPmDao userPmDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PlatConfigService platConfigService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private SupUserRecordDao supUserRecordDao;
    /**
     * 权益初始信用分key
     */
    private static final String EQUITY_INITIAL_CREDIT = "equity_initial_credit";


    /**
     * 模糊查询会员id
     *
     * @param userAccountOrName 会员编号或名称
     * @return
     */
    @Override
    public String getUserId(String userAccountOrName) {
        List<Integer> userIds = userDao.queryUserIdByBlurName(userAccountOrName);
        if (userIds.isEmpty()) {
            return null;
        }
        int maxUser = 500;
        if (userIds.size() >= maxUser) {
            return "toomuch";
        }
        StringBuilder userIdContainer = new StringBuilder(userIds.size() * 7);
        for (Integer item : userIds) {
            userIdContainer.append(item).append(",");
        }
        return StringUtils.removeEnd(userIdContainer.toString(), ",");
    }

    /**
     * 检验模糊查询会员id数量
     *
     * @param userid 会员id
     * @return
     */
    @Override
    public Page dealUserid(String userid) {
        Page page = new Page();
        if (userid == null) {
            page.setQueryBean(MessageBean.fail("不存在的会员"));
            page.setTotal(0);
            page.setResultList(new ArrayList());
            return page;
        } else {
            page.setQueryBean(MessageBean.fail("匹配到的会员太多了"));
            page.setTotal(0);
            page.setResultList(new ArrayList());
            return page;
        }
    }

    /**
     * 查询会员信息
     *
     * @param supUser   会员实体
     * @param page      分页组件
     * @param startTime 查询开始时间
     * @param endTime   查询结束时间
     * @param include   0包含，1剔除
     * @param auditType 供卡审核状态
     * @return
     */
    @Override
    public Page getUser(SupUser supUser, Page page, String startTime, String endTime, Integer include, String auditType) {
        int total = userDao.querySupUserCount(supUser, startTime, endTime, include, auditType);
        page.setTotal(total);
        if (total == 0) {
            page.setResultList(new ArrayList<>());
        } else {
            page.setResultList(userDao.querySupUser(supUser, page, startTime, endTime, include, auditType));
        }
        return page;
    }

    /**
     * 根据账号查询会员信息
     *
     * @param account 账号/别名
     * @return 会员
     */
    @Override
    public SupUser queryUsersByAccount(String account) {
        return userDao.querySupUsersByAccount(account);
    }

    /**
     * 会员锁定: 锁定后会员无法登陆（密码错误过多解绑）
     *
     * @param account 会员编号
     * @param state   1 锁定 0 解锁
     * @return MessageBean
     */
    @Override
    public MessageBean unLockUser(String account, Integer state) {
        SupUser supUser = queryUsersByAccount(account);
        if (supUser == null) {
            return MessageBean.fail("找不到该会员!");
        }
        if (state == 0) {
            SimpleCacheUtil.removeObject(account + SupRedisKey.SupUserLock);
        } else {
            SimpleCacheUtil.setObject(account + SupRedisKey.SupUserLock, 6);
        }
        return MessageBean.success();
    }

    /**
     * 查询注册黑名单
     *
     * @param accountOrIp 手机号/ip
     * @param type        类型，IP/No
     * @return list
     */
    @Override
    public List<HashMap<String, Object>> queryRegisterBlackList(String accountOrIp, String type) {
        String cacheKey = org.apache.commons.lang.StringUtils.isBlank(accountOrIp) ? "*" + type + "*" : "*" + type + accountOrIp + "*";
        List<HashMap<String, Object>> resultList = new ArrayList<>();
        Set<String> keys = redisTemplate.keys(cacheKey);
        if (keys == null || keys.isEmpty()) {
            return Collections.emptyList();
        }
        for (String key : keys) {
            HashMap<String, Object> resultMap = new HashMap<>(2);
            int index = key.indexOf("SUP_R");
            key = key.substring(index, key.length());
            Integer banCount = Integer.valueOf((String) SimpleCacheUtil.getObject(key));
            if (banCount == null) {
                continue;
            }
            switch (type) {
                case "IP":
                    if (9 <= banCount) {
                        resultMap.put("data", key);
                        resultList.add(resultMap);
                    }
                    break;
                default:
                    if (4 <= banCount) {
                        resultMap.put("data", key);
                        resultList.add(resultMap);
                    }
            }

        }
        return resultList;
    }

    /**
     * 移除注册黑名单
     *
     * @param data 黑名单信息
     */
    @Override
    public void removeBlackList(String data) {
        if (SimpleCacheUtil.getObject(data) == null) {
            return;
        }
        SimpleCacheUtil.removeObject(data);
    }

    /**
     * 新增IP黑名单
     *
     * @param ip 黑名单ip
     */
    @Override
    public void createIpBlack(String ip) {
        SimpleCacheUtil.setObject(SupRedisKey.SUP_RIP + ip, 11);
    }

    /**
     * 导出IP黑名单信息
     *
     * @param accountOrIp ip
     * @param type
     * @param response
     */
    @Override
    public void downloadUserInfoList(String accountOrIp, String type, HttpServletResponse response) {
        BufferedWriter writer = null;
        try {
            String cacheKey = org.apache.commons.lang.StringUtils.isBlank(accountOrIp) ? "*SUP_R" + type + "*" : "SUP_R" + type + accountOrIp;
            Object cacheValue = SimpleCacheUtil.getObject(cacheKey);
            response.setContentType("application/octet-stream;charset=GBK");
            String fileName = "userIpBlack" + System.currentTimeMillis() + ".csv";
            writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "GBK"));
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            StringBuilder csv = new StringBuilder();
            List<SupUser> queryList = userDao.downloadUserInfoList(accountOrIp);
            if (queryList.size() == 0) {
                IOUtils.write("<script>无记录</script>".getBytes("GBK"), writer, "UTF-8");
                writer.flush();
                return;
            }
            for (SupUser aQueryList : queryList) {
                csv.append(aQueryList.getAccount()).append(",").append(aQueryList.getSupInfo().getName() + "\r\n");
            }
            writer.write("账号,名称\r\n");
            writer.write(csv.toString());
            writer.flush();
        } catch (Exception ex) {
            log.warn("IP黑名单用户表查询出错{}", ex, ex);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    /**
     * 修改会员支付密码
     *
     * @param account 账号
     * @param payPwd  支付密码
     * @return MessageBean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MessageBean updatePayPwd(String account, String payPwd) {
        SupUser user = queryUsersByAccount(account);
        if (null == user) {
            return MessageBean.fail("找不到该会员！");
        }
        String payPwdMd5 = Md5.getMd5(payPwd, true, "UTF-8");
        user.setPayPwd(payPwdMd5);
        if (userDao.modifySupUser(user) != 1) {
            return MessageBean.fail("修改支付密码失败");
        }
        return MessageBean.success();
    }

    /**
     * 查询同一ip注册多少账号
     *
     * @param ip ip
     * @return list
     */
    @Override
    public List<SupUser> queryUserByIp(String ip) {
        return userDao.downloadUserInfoList(ip);
    }

    /**
     * 查询会员权限
     *
     * @param supUser 用户信息
     * @return 返回权限信息
     */
    @Override
    public SupPrivilege queryPrivilege(SupUser supUser) {
        return userDao.querySupPrivilege(supUser.getUserId());

    }

    /**
     * 修改会员权限
     *
     * @param supPrivilege 会员权限
     * @return MessageBean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public MessageBean updatePrivilege(SupPrivilege supPrivilege) throws Exception {
        AdminVO admin = adminService.getCurrentAdmin();
        SupUser user = userDao.queryUserById(supPrivilege.getUserId());
        if (null == user) {
            return MessageBean.fail("找不到该会员！");
        }
        SupPrivilege dbPrivilege = userDao.querySupPrivilege(user.getUserId());
        if (userDao.modifySupPrivilege(supPrivilege) != 1) {
            return MessageBean.fail();
        }
        if (supPrivilege.getSupplyState() == null) {
            return MessageBean.success();
        }
        if (dbPrivilege.getSupplyState().equals(supPrivilege.getSupplyState())) {
            return MessageBean.success();
        }
        SubmitCardApplyEnum apply = SubmitCardApplyEnum.INIT;
        String record = "关闭供卡权限";
        if (1 == supPrivilege.getSupplyState()) {
            apply = SubmitCardApplyEnum.SUCCESS;
            record = "开启供卡权限";
        }
        userDao.modifySubmitCardApply(user.getUserId(), apply);
        supUserRecordDao.create(SupUserRecord.builder().userId(user.getUserId()).administer(admin.getName()).record(record).build());
        return MessageBean.success();
    }

    /**
     * 批量修改会员编号状态；接口状态
     *
     * @param userIds   会员id
     * @param status    状态 0：开启 1：关闭
     * @param privilege accountStatus 账号状态  apiState：接口状态
     * @return
     */
    @Override
    public MessageBean updateUserStatus(Long[] userIds, Integer status, String privilege) {
        for (Long userId : userIds) {
            SupUser supUser = new SupUser();
            supUser.setUserId(userId);
            if ("accountStatus".equals(privilege)) {
                supUser.setStatus(status);
            } else if ("apiState".equals(privilege)) {
                supUser.setApiState(status);
            } else if ("equityApiState".equals(privilege)) {
                supUser.setEquityApiState(status);
            }
            userDao.modifySupUser(supUser);
        }
        return MessageBean.success();
    }

    /**
     * 修改会员信息
     *
     * @param supUser 会员
     * @return MessageBean
     */
    @Override
    public MessageBean updateSupUser(SupUser supUser) {
        if (Objects.nonNull(supUser.getUserPm())) {
            if (StringUtils.isNotBlank(supUser.getUserPm().getName())) {
                UserPm userPm = userPmDao.queryUserPm(supUser.getUserPm().getName());
                if (Objects.nonNull(userPm)) {
                    supUser.setPmId(userPm.getId());
                } else {
                    return MessageBean.fail("该PM不存在");
                }
            }
        }
        if (userDao.modifySupUser(supUser) != 1) {
            return MessageBean.fail();
        }
        if (supUser.getSupInfo() != null) {
            supUser.getSupInfo().setUserId(supUser.getUserId());
            if (userDao.modifySupUserInfo(supUser.getSupInfo()) != 1) {
                return MessageBean.fail();
            }
        }
        return MessageBean.success();
    }

    /**
     * 重置登录密码
     *
     * @param userId 会员id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MessageBean resetUserLoginPwd(Long userId) {
        SupUser user = userDao.queryUserById(userId);
        if (user == null) {
            return MessageBean.fail("查询会员信息失败");
        }
        if (org.apache.commons.lang.StringUtils.isEmpty(user.getSupInfo().getEmail())) {
            return MessageBean.fail("该会员尚未绑定邮箱！");
        }
        String code = RandomStringUtils.randomAlphabetic(1) + RandomStringUtils.randomAlphanumeric(4)
                + RandomStringUtils.randomNumeric(1);
        String cCode = Md5.getMd5(code, true, "UTF-8");
        user.setLoginPwd(cCode);
        int res = userDao.modifySupUser(user);
        if (res != 1) {
            throw new OperateFailException("更新会员登陆密码失败，期望值:1,实际值:" + res);
        }
        String title = "豆乐卡卡密兑换平台会员登陆密码";
        if (!EmailSend.send(user.getSupInfo().getEmail(), title,
                "尊敬的豆乐卡用户您好 ： \n系统为您重置的登陆密码为：" + code + " (建议登陆之后自行修改密码。该邮件不需要回复，谢谢！)【豆乐卡】\n")) {
            throw new OperateFailException("邮件发送失败！");
        }
        return MessageBean.success();
    }

    public static void main(String[] args) {
        String code = RandomStringUtils.randomAlphabetic(1) + RandomStringUtils.randomAlphanumeric(4)
                + RandomStringUtils.randomNumeric(1);
        String cCode = Md5.getMd5(code, true, "UTF-8");
        //code=YCAaT7,code2=F97C625732CD12A10A2EEA61E696FDA6
        System.out.println("code=" + code + ",code2=" + cCode);
    }

    /**
     * 新建会员信息
     *
     * @param supUser 会员
     * @return MessageBean
     */
    @Override
    public MessageBean insertSupUser(SupUser supUser) {
        SupUser user = userDao.querySupUsersByAccount(supUser.getAccount());
        if (Objects.nonNull(user)) {
            return MessageBean.fail("会员已存在!");
        }
        if (Objects.nonNull(supUser.getUserPm())) {
            if (StringUtils.isNotBlank(supUser.getUserPm().getName())) {
                UserPm userPm = userPmDao.queryUserPm(supUser.getUserPm().getName());
                if (Objects.nonNull(userPm)) {
                    supUser.setPmId(userPm.getId());
                } else {
                    return MessageBean.fail("该PM不存在");
                }
            }
        }
        String userKey = StringUtils.replace(UUID.randomUUID().toString(), "-", "").trim();
        supUser.setUserKey(userKey);
        supUser.setEquityCredit(new BigDecimal(platConfigService.queryPlatConfigBykey(EQUITY_INITIAL_CREDIT)));
        if (userDao.insertSupUser(supUser) != 1) {
            return MessageBean.fail();
        }
        SupUser dbSupUser = userDao.querySupUsersByAccount(supUser.getAccount());
        if (Objects.isNull(dbSupUser)) {
            return MessageBean.fail();
        }
        //新建用户详情
        if (supUser.getSupInfo() != null) {
            supUser.getSupInfo().setUserId(dbSupUser.getUserId());
            if (userDao.createSupUserInfo(supUser.getSupInfo()) != 1) {
                return MessageBean.fail();
            }
        }
        //创建余额信息
        int supBalance = supplyFinanceDao.createSupplyBalance(dbSupUser.getUserId());
        if (supBalance == 0) {
            return MessageBean.fail();
        }
        //创建用户权限
        int supPrivilege = userDao.createSupPrivilege(dbSupUser.getUserId());
        if (supPrivilege == 0) {
            return MessageBean.fail();
        }
        return MessageBean.success();
    }

    /**
     * 根据id查询会员信息
     *
     * @param userId 会员id
     * @return 返回会员信息
     */
    @Override
    public SupUser queryUsersById(Long userId) {
        return userDao.queryUserById(userId);
    }

    /**
     * 会员IP解锁
     *
     * @param ip 会员ip
     * @return MessageBean
     */
    @Override
    public MessageBean unLockUserIp(String ip) {
        SimpleCacheUtil.removeObject(ip + SupRedisKey.SupUserLock);
        return MessageBean.success();
    }

    /**
     * 会员信息导出
     *
     * @param supUser   会员实体
     * @param startTime 查询开始时间
     * @param endTime   查询结束时间
     * @param include   0包含，1剔除
     * @return
     */
    @Override
    public void downLoad(SupUser supUser, String startTime, String endTime, Integer include, String auditType, HttpServletResponse response) {
        int total = userDao.querySupUserCount(supUser, startTime, endTime, include, auditType);
        BufferedWriter bufferedWriter = null;
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment;filename=" + System.currentTimeMillis() + ".csv");
            Page page = new Page();
            page.setSize(5000);
            page.setTotal(total);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(servletOutputStream, "GBK"));
            bufferedWriter.write("会员编号,会员名称,状态,供卡接口状态,权益接口状态,供卡审核状态,销卡模板,注册时间,PM,会员来源,绑定IP,权益信用分");
            bufferedWriter.newLine();
            while (page.getPage() <= page.getMaxPage()) {
                List<SupUser> list = userDao.querySupUser(supUser, page, startTime, endTime, include, auditType);
                int size = list.size();
                StringBuffer data = new StringBuffer(size * 100);
                for (int i = 0; i < size; i++) {
                    data.append(list.get(i));
                }
                bufferedWriter.write(StringUtils.replace(data.toString(), "null", ""));
                page.setPage(page.getPage() + 1);
            }
            bufferedWriter.flush();
        } catch (Exception e) {
            log.warn("会员信息导出出错{}", e, e);
        } finally {
            IOUtils.closeQuietly(bufferedWriter);
        }
    }

    /**
     * 开启api会员自动异步
     *
     * @param userId 会员id
     * @return
     */
    @Override
    public MessageBean autoAsyn(Long userId) {
        if (userDao.queryUserById(userId) == null) {
            return MessageBean.fail("会员不存在");
        }
        if (SimpleCacheUtil.getKeyObject(SupRedisKey.AUTO_ASYN.toString() + userId) == null) {
            return MessageBean.fail("该会员自动异步未暂停");
        }
        SimpleCacheUtil.removeObject(SupRedisKey.AUTO_ASYN.toString() + userId);
        SimpleCacheUtil.removeObject(SupRedisKey.ASYN_ABNORMAL_COUNT.toString() + userId);
        //查询会员未异步的订单
        List<SupplyCard> supplyCardList = orderDao.queryAsynchronousCard(userId);
        StringBuilder orderIds = new StringBuilder();
        supplyCardList.forEach(card -> {
            orderIds.append(card.getOrderId()).append(",");
        });
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("orderIds", StringUtils.removeEnd(orderIds.toString(), ",")));
        StringBuffer url = new StringBuffer(PlatConfigUtil.getProperty("plat-url.properties", "SUPMemberSys"));
        url.append("supply/apiCardSupplyCallBack");
        String result = Httpclient.post(url.toString(), params, "utf-8", 3000, 3000);
        log.info("sup收卡管理平台请求SUP会员系统添加到API提卡回调队列url[{}]请求串:[{}]返回:[{}]", url, orderIds, result);
        //请求超时
        if (StringUtils.isBlank(result)
                || StringUtils.equalsIgnoreCase("读取超时", result)) {
            log.warn("sup收卡管理平台请求SUP会员系统请求超时url[{}]请求串:[{}]", url, orderIds);
            return MessageBean.fail("会员异步订单提交失败");
        }
        if (StringUtils.isBlank(result)
                || StringUtils.equalsIgnoreCase("请求异常", result)) {
            log.warn("sup收卡管理平台请求SUP会员系统请求超时url[{}]请求串:[{}]", url, orderIds);
            return MessageBean.fail("会员异步订单提交失败");
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode jsonNode = mapper.readTree(result);
            if (Objects.isNull(jsonNode)) {
                return MessageBean.fail("会员异步订单提交失败");
            }
            JsonNode status = jsonNode.get("status");
            if (status != null && 0 != status.asInt()) {
                return MessageBean.fail("会员异步订单提交失败");
            }
        } catch (IOException e) {
            log.warn("json解析异常[{}]", result);
            return MessageBean.fail("会员异步订单提交失败");
        }
        return MessageBean.success();
    }

    /**
     * 修改权益信用分
     *
     * @param userIds      会员id
     * @param equityCredit 权益信用分
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MessageBean updateEquityCredit(Long[] userIds, BigDecimal equityCredit, String remark) throws Exception {
        AdminVO currentAdmin = adminService.getCurrentAdmin();
        for (Long userId : userIds) {
            SupUser supUser = userDao.queryUserById(userId);
            EquityCreditModify equityCreditModify = new EquityCreditModify(userId, supUser.getEquityCredit(), equityCredit, currentAdmin.getName(), remark);
            userDao.updateEquityCredit(userId, equityCredit);
            userDao.insertEquityCreditModify(equityCreditModify);
        }
        return MessageBean.success();
    }

    /**
     * 查询权益信用分修改记录
     *
     * @param equityCreditModify 会员实体
     * @param page               分页组件
     * @param startTime          查询开始时间
     * @param endTime            查询结束时间
     * @return
     */
    @Override
    public Page queryEquityCreditModify(EquityCreditModify equityCreditModify, Page page, String startTime, String endTime) {
        int total = userDao.queryEquityCreditModifyCount(equityCreditModify, startTime, endTime);
        page.setTotal(total);
        if (total == 0) {
            page.setResultList(new ArrayList<>());
        } else {
            page.setResultList(userDao.queryEquityCreditModify(equityCreditModify, page, startTime, endTime));
        }
        return page;
    }

    /**
     * 会员佣金展示状态获取 true 开启 false 关闭
     *
     * @return
     */
    @Override
    public boolean getCommissionStatus() {
        return false;
    }

    /**
     * 闲鱼佣金展示开关
     *
     * @param status
     * @return
     * @throws SupException
     */
    @Override
    public void updateCommissionStatus(Integer status) throws SupException {
    }

    /**
     * 分页查询会员操作记录
     *
     * @param page   分页组件
     * @param userId 会员id
     * @return page
     */
    @Override
    public Page<SupUserRecord> queryUserRecordPage(Page<SupUserRecord> page, Long userId) {
        int total = userDao.queryUserRecordCount(userId);
        page.setTotal(total);
        if (total == 0) {
            page.setResultList(Collections.emptyList());
        } else {
            page.setResultList(userDao.queryUserRecordPage(page, userId));
        }
        return page;
    }

    /**
     * 审核会员供卡申请
     *
     * @param userId 会员id
     * @param apply  审核状态
     * @param remark 备注
     * @return MessageBean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public MessageBean auditSubmitCardApply(Long userId, SubmitCardApplyEnum apply, String remark) throws Exception {
        AdminVO admin = adminService.getCurrentAdmin();
        SupUser user = userDao.queryUserById(userId);
        if (null == user) {
            return MessageBean.fail("找不到该会员！");
        }
        // 审核成功，开启供卡权限
        int supplyState = 1;
        if (SubmitCardApplyEnum.SUCCESS == apply) {
            remark = "审核成功；" + remark;
        } else {
            remark = "审核失败；" + remark;
            supplyState = 0;
        }
        if (userDao.modifySupPrivilege(SupPrivilege.builder().userId(userId).supplyState(supplyState).build()) != 1) {
            return MessageBean.fail();
        }
        userDao.modifySubmitCardApply(userId, apply);
        supUserRecordDao.create(SupUserRecord.builder().userId(userId).administer(admin.getName()).record(remark).build());
        return MessageBean.success();
    }
}
